import { createSlice } from "@reduxjs/toolkit";

export const propertylist = createSlice({
  name: "propertylist",
  initialState: {
    // 楼层列表数据
    // 数据持久化
    pList: JSON.parse(localStorage.getItem("pList")) || [],
  },

  reducers: {
    // 楼层列表渲染数据
    pListSet: (state, action) => {
      state.pList = action.payload;
      // 数据持久化
      localStorage.setItem("pList", JSON.stringify(action.payload));
    },
    pListItemStateChe: (state, action) => {
      let index = state.pList.findIndex((item) => item.id == action.payload);
      state.pList[index].state = !state.pList[index].state;
    },
    //  删除
    delProperty1: (state, action) => {
      // alert("确认删除")
      const indexitem = state.pList.findIndex(
        (item) => item.key === action.payload.key
      );
      state.pList.splice(indexitem, 1);
      // console.log(action.payload);
    },

    // 勾选删除
    deleRow: (state, action) => {
      const newArr = [...state.pList];
      // 循环删除行
      action.payload.forEach((item) => {
        const index = newArr.findIndex((arr) => arr.key === item);
        newArr.splice(index, 1);
      });
      state.pList = newArr;
    },
    // 编辑
    editProperty: (state, action) => {
      // console.log(action.payload);
    },

    // 搜索
    searchProperty1: (state, action) => {
      const { payload } = action;
      let newlist = [...state.pList];
      if (payload.region) {
        newlist = newlist.filter((item, index) => {
          return item.region === payload.region;
        });
      }

      if (payload.status) {
        newlist = newlist.filter((item, index) => {
          return item.state === (payload.status === 1 ? true : false);
        });
      }

      if (payload.name) {
        newlist = newlist.filter((item, index) => {
          return item.name.includes(payload.name);
        });
      }

      state.pList = newlist;
      console.log(action.payload);
    },

    pListItemStateChe: (state, action) => {
      console.log(action.payload);
      let index = state.pList.findIndex((item) => item.id == action.payload);
      state.pList[index].state = !state.pList[index].state;
    },
    // 添加楼盘
    addProperty: (state, action) => {
      console.log(action.payload, "添加的数据");
      state.pList.unshift(action.payload);
    },
  },
});
// 每个 case reducer 函数会生成对应的 Action creators
// 导出切片中的方法
export const {
  pListSet,
  pListItemStateChe,
  // 楼盘编辑
  editProperty,
  // 楼盘删除
  delProperty1,
  // 楼盘添加
  addProperty,
  // 搜索
  searchProperty1,
  // 勾选删除
  deleRow,
} = propertylist.actions;

export default propertylist.reducer;
